package com.example.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.db.CommonData;
import com.example.im.ChatActivity;
import com.example.im.R;
import com.example.model.Friends;
import com.example.model.Msg;
import com.example.model.User;
import com.example.util.MyUtil;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import static com.example.db.CommonData.addDbFriend;
import static com.example.db.CommonData.addDbMsg;
import static com.example.db.CommonData.commonData;
import static com.example.db.CommonData.getDbMsg;
import static com.example.util.MyUtil.exeUrlTask;
import static com.example.util.MyUtil.toast;

public class FriendListAdapter extends BaseAdapter {
    private final LayoutInflater inflater;
    private final List<Friends> mData;

    private final Context context;

    public FriendListAdapter(Context context, List<Friends> data) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // 要绑定的条目的数目
    @Override
    public int getCount() {
        return mData.size();
    }

    // 根据一个索引（位置）获得该位置的对象
    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    // 获取条目的id
    @Override
    public long getItemId(int position) {
        return position;
    }

    // 获取该条目要显示的界面
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        FriendHolder holder;
        // 第一次加载条目时，初始化界面和相应函数
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.message_list_item, parent, false);
            holder = new FriendHolder();

            holder.name = (TextView) convertView.findViewById(R.id.friend_name);
            holder.msg = (TextView) convertView.findViewById(R.id.msg_log);
            convertView.setTag(holder);

            convertView.setOnClickListener(e -> {
//                //点击跳转聊天页面，并将好友信息传过去
//                Intent intent = new Intent(context, ChatActivity.class);
//                //创建Bundle，放置Person对象
//                Bundle data = new Bundle();
                Friends friend = mData.get(position);
                //保存好友信息
                friend.setStatus(1);
                commonData.setChatFriend(friend);
                MyUtil.changeActivity((Activity) context,ChatActivity.class);
//                //intent携带Bundle
//                intent.putExtras(data);
//                //启动对应的Activity
//                context.startActivity(intent);
            });
        } else {
            holder = (FriendHolder) convertView.getTag();
        }
        Friends friend = mData.get(position);
        holder.name.setText(friend.getName());
        MyUtil.initFirstMsg(friend.getName(),friend.getFid(),context);
        holder.msg.setText(friend.getLatestMsg());

        return convertView;
    }

    public void flash() {
        exeUrlTask(
                context,
                () -> MyUtil.getReqParam("/imChatUserFriend/getFriend",
                        MyUtil.paramMap(Collections.singletonList("friendStatus"),
                                Collections.singletonList("1"))),
                res -> {
                    /* 数组
                    {
                        "id": 1,
                        "userId": 2,
                        "friendId": 1,
                        "username": "Sara",
                        "gender": 1,
                        "avatar": "",
                        "introduction": "",
                        "friendStatus": 1,
                        "remark": "站长",
                        "createTime": "2024-01-05 14:29:23"
                    }
                     */
                    JSONArray arr = res.getDataArray();
                    // 重置好友列表
                    commonData.friendDb = new HashMap<>();
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject data = arr.getJSONObject(i);
//                            String remark = data.getString("remark");
                        String name = data.getString("username");
                        int id = data.getInteger("id");
                        int uid = data.getInteger("friendId");
                        Friends f = new Friends();
                        f.setLatestMsg("");
                        f.setName(name);
                        f.setFid(uid);
                        f.setId(id);
                        f.setStatus(data.getInteger("friendStatus"));
                        f.setUid(commonData.getLoginUserId());
                        User fUser = new User();
                        fUser.setName(name);
                        fUser.setId(uid);
//                        MyUtil.initFirstMsg(f.getName(),f.getFid(),context);
                        // 添加或更新好友信息
                        CommonData.addDbFriend(commonData.getUser(), fUser);
                    }

                    mData.clear();
                    mData.addAll(CommonData.getDbFriendList(commonData.getUser().getName()));
//                    toast(context,"查询好友列表成功");
                    notifyDataSetChanged();
                },
                (res) -> {
                    // 请求网络失败时处理方案：直接取本地
                    List<Friends> dbFriendList = CommonData.getDbFriendList(commonData.getUser().getName());
                    mData.clear();
                    mData.addAll(dbFriendList);
                    notifyDataSetChanged();
//                    toast(context,"查询本地好友列表成功");
                }
        );


    }


    // 新建holder类，对listview进行简单优化
    public static class FriendHolder {
        Button addFriendButton;
        TextView name;
        TextView id;
        TextView msg;
    }
}